package com.echo.code.arithmetic.chapter02;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * Created by baiyap on 2018/7/27.
 */
public class SelectionSort {

  public static void main(String[] args) {
    List<Integer> list = new LinkedList<Integer>(Arrays.asList(5, 3, 6, 2, 2, 10));
    List<Integer> sortedList = selectionSort(list);
    System.out.println(sortedList);
  }

  private static List<Integer> selectionSort(List<Integer> list) {
    Objects.requireNonNull(list, "invalid parameter");
    List<Integer> newList = new LinkedList<>();
    while (!list.isEmpty()) {
      int smallest_index = findSmallest(list);
      newList.add(list.remove(smallest_index));
    }
    return newList;
  }

  private static int findSmallest(List<Integer> list) {
    int smallest_index = 0;
    int smallest = list.get(smallest_index);
    for (int i = 0; i < list.size(); i++) {
      if (list.get(i) < smallest) {
        smallest_index = i;
        smallest = list.get(i);
      }
    }
    return smallest_index;
  }
}
